<template>
  <div class="app-container home">
    <div style="margin-bottom: 20px; text-align: right;">
      <el-button type="primary" icon="el-icon-refresh" @click="getCustomerStats">刷新数据</el-button>
    </div>
    <el-row :gutter="20">
      <!-- 第一个卡片：各学校使用时长统计 -->
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>各学校使用时长统计</span>
          </div>
          <div class="chart-container">
            <div
              id="schoolUsageChart"
              ref="schoolUsageChart"
              class="chart"
            ></div>
          </div>
        </el-card>
      </el-col>

      <!-- 第二个卡片：各模式使用比例 -->
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>各模式使用比例</span>
          </div>
          <div class="chart-container">
            <div id="modeUsageChart" ref="modeUsageChart" class="chart"></div>
          </div>
        </el-card>
      </el-col>

      <!-- 第三个卡片：年级使用趋势 -->
      <el-col :span="12" style="margin-top: 20px">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>班级使用趋势</span>
          </div>
          <div class="chart-container">
            <div id="gradeTrendChart" ref="gradeTrendChart" class="chart"></div>
          </div>
        </el-card>
      </el-col>

      <!-- 第四个卡片：班级使用时长排行 -->
      <el-col :span="12" style="margin-top: 20px">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>班级使用时长排行</span>
          </div>
          <div class="chart-container">
            <div
              id="classRankingChart"
              ref="classRankingChart"
              class="chart"
            ></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { customerStats } from "@/api/custmoer";

import * as echarts from "echarts";
import { mapGetters } from "vuex";
require("echarts/theme/macarons"); // echarts theme

export default {
  name: "Index",
  data() {
    return {
      // 版本号
      version: "3.9.0",
      // 模拟数据
      schoolUsageData: [

      ],
      modeUsageData: [],
      gradeTrendData: {
        grades: [],
        usageHours: [],
      },
      classRankingData: [

      ],
      // 图表实例
      charts: {},
    };
  },
  computed: {
    ...mapGetters([
      "sidebar", // 从vuex获取侧边栏状态，用于响应式调整图表大小
    ]),
  },
  watch: {
    sidebar() {
      this.$nextTick(() => {
        this.resizeCharts();
      });
    },
  },
  mounted() {
    // this.$nextTick(() => {
    //   // 初始化所有图表
    //   this.initSchoolUsageChart();
    //   this.initModeUsageChart();
    //   this.initGradeTrendChart();
    //   this.initClassRankingChart();
    // });
    this.getCustomerStats();

    // 监听窗口大小变化，调整图表大小
    window.addEventListener("resize", this.resizeCharts);
  },
  beforeDestroy() {
    // 销毁图表实例
    Object.keys(this.charts).forEach((key) => {
      if (this.charts[key]) {
        this.charts[key].dispose();
        this.charts[key] = null;
      }
    });
    // 移除事件监听
    window.removeEventListener("resize", this.resizeCharts);
  },
  methods: {
    // 获取客户统计数据
    getCustomerStats() {
      console.log("获取客户统计数据");
      // 清空旧数据
      this.schoolUsageData = []
      this.modeUsageData = []
      this.gradeTrendData.grades = []
      this.gradeTrendData.usageHours = []
      this.classRankingData = []
      try {
        customerStats().then((res) => {
          res.device_mode.forEach(item=>{
            this.modeUsageData.push({
              name: item.device_mode,
              value: Number(item.total_duration_seconds),
            })
          })
          this.schoolUsageData=res.school

          res.school_class.forEach(item=>{
            this.gradeTrendData.grades.push(item.name)
            this.gradeTrendData.usageHours.push(Number(item.value))
          })
          if(this.gradeTrendData.grades.length>10){
           this.gradeTrendData.grades=this.gradeTrendData.grades.slice(0,10)
           this.gradeTrendData.usageHours=this.gradeTrendData.usageHours.slice(0,10)
          }
          res.school_class_ranking.forEach(item=>{
            this.classRankingData.push({
              name: item.name,
              hours: Number(item.value),
            })
          })
          this.initSchoolUsageChart();
          this.initModeUsageChart();
          this.initGradeTrendChart();
          this.initClassRankingChart();
        });

        // if (res.code === 200) {
        //   this.schoolUsageData = res.data.school_usage
        //   this.modeUsageData = res.data.mode_usage
        //   this.gradeTrendData = res.data.grade_trend
        //   this.classRankingData = res.data.class_ranking
        //   // 刷新图表
        //   this.initSchoolUsageChart()
        //   this.initModeUsageChart()
        //   this.initGradeTrendChart()
        //   this.initClassRankingChart()
        // }
      } catch (error) {
        console.error("获取客户统计数据失败:", error);
      }
    },
    // 初始化学校使用时长柱状图
    initSchoolUsageChart() {
      if (!this.$refs.schoolUsageChart) return;
      const chart = echarts.init(this.$refs.schoolUsageChart, "macarons");
      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          formatter: "{b}: {c} 秒",
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: this.schoolUsageData.map((item) => item.name),
          axisLabel: {
            rotate: 30,
          },
        },
        yAxis: {
          type: "value",
          name: "使用时长(秒钟)",
        },
        series: [
          {
            name: "使用时长",
            type: "bar",
            data: this.schoolUsageData.map((item) => item.value),
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "#83bff6" },
                { offset: 0.5, color: "#188df0" },
                { offset: 1, color: "#188df0" },
              ]),
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: "#2378f7" },
                  { offset: 0.7, color: "#2378f7" },
                  { offset: 1, color: "#83bff6" },
                ]),
              },
            },
          },
        ],
      };
      chart.setOption(option);
      this.charts.schoolUsageChart = chart;
    },

    // 初始化模式使用比例饼图
    initModeUsageChart() {
      if (!this.$refs.modeUsageChart) return;
      const chart = echarts.init(this.$refs.modeUsageChart, "macarons");

      // 计算总时长和百分比
      const totalDuration = this.modeUsageData.reduce((sum, item) => sum + item.value, 0);

      const option = {
        tooltip: {
          trigger: "item",
          formatter: (params) => {
            const { name, value, percent } = params;
            const hours = Math.floor(value / 3600);
            const minutes = Math.floor((value % 3600) / 60);
            const seconds = value % 60;

            let timeStr = '';
            if (hours > 0) timeStr += `${hours}小时`;
            if (minutes > 0) timeStr += `${minutes}分钟`;
            if (seconds > 0 || timeStr === '') timeStr += `${seconds}秒`;

            return `
              <div style="font-weight: bold; margin-bottom: 5px;">${name}</div>
              <div>使用时长: ${timeStr}</div>
              <div>占比: ${percent}%</div>

            `;
          },
        },
        legend: {
          orient: "vertical",
          left: "left",
          data: this.modeUsageData.map((item) => item.name),
        },
        series: [
          {
            name: "使用模式1",
            type: "pie",
            radius: "55%",
            center: ["50%", "60%"],
            data: this.modeUsageData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
            label: {
              formatter: (params) => {
                const { name, value } = params;
                const hours = Math.floor(value / 3600);
                const minutes = Math.floor((value % 3600) / 60);
                const seconds = value % 60;

                let timeStr = '';
                if (hours > 0) timeStr += `${hours}小时`;
                if (minutes > 0) timeStr += `${minutes}分钟`;
                if (seconds > 0 || timeStr === '') timeStr += `${seconds}秒`;

                return `${name}: ${timeStr}`;
              },
            },
          },
        ],
      };
      chart.setOption(option);
      this.charts.modeUsageChart = chart;
    },

    // 初始化年级使用趋势折线图
    initGradeTrendChart() {
      if (!this.$refs.gradeTrendChart) return;
      const chart = echarts.init(this.$refs.gradeTrendChart, "macarons");
      const option = {
        tooltip: {
          trigger: "axis",
          formatter: "{b}: {c} 秒",
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: this.gradeTrendData.grades,
        },
        yAxis: {
          type: "value",
          name: "使用时长(秒)",
        },
        series: [
          {
            name: "使用时长",
            type: "line",
            stack: "总量",
            data: this.gradeTrendData.usageHours,
            smooth: true,
            symbol: "circle",
            symbolSize: 8,
            itemStyle: {
              color: "#1890ff",
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgba(24, 144, 255, 0.5)" },
                { offset: 1, color: "rgba(24, 144, 255, 0.1)" },
              ]),
            },
          },
        ],
      };
      chart.setOption(option);
      this.charts.gradeTrendChart = chart;
    },

    // 初始化班级使用时长排行条形图
    initClassRankingChart() {
      if (!this.$refs.classRankingChart) return;
      const chart = echarts.init(this.$refs.classRankingChart, "macarons");
      // 对班级数据按使用时长排序
      const sortedClassData = [...this.classRankingData].sort(
        (a, b) => b.hours - a.hours
      );

      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          formatter: "{b}: {c} 秒",
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "value",
          name: "使用时长(秒)",
        },
        yAxis: {
          type: "category",
          data: sortedClassData.map((item) => item.name),
          axisLabel: {
            interval: 0,
          },
        },
        series: [
          {
            name: "使用时长",
            type: "bar",
            data: sortedClassData.map((item) => item.hours),
            itemStyle: {
              color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                { offset: 0, color: "#83bff6" },
                { offset: 0.5, color: "#188df0" },
                { offset: 1, color: "#188df0" },
              ]),
            },
          },
        ],
      };
      chart.setOption(option);
      this.charts.classRankingChart = chart;
    },

    // 调整所有图表大小
    resizeCharts() {
      Object.keys(this.charts).forEach((key) => {
        if (this.charts[key]) {
          this.charts[key].resize();
        }
      });
    },

    goTarget(href) {
      window.open(href, "_blank");
    },
  },
};
</script>

<style scoped lang="scss">
.home {
  padding: 20px;

  .chart-container {
    height: 300px;
    position: relative;

    .chart {
      width: 100%;
      height: 100%;
    }
  }

  .box-card {
    height: 100%;
    display: flex;
    flex-direction: column;

    // /deep/ .el-card__body {
    //   flex: 1;
    //   padding: 15px;
    //   display: flex;
    //   flex-direction: column;
    // }
  }
}
</style>

